const mongoose = require('mongoose')

// 连接数据库
mongoose.connect(process.env.DB_CONNECTION_STRING || 'mongodb://localhost:27017/totp-generator', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})

// TOTP验证码模型
const totpCodeSchema = new mongoose.Schema({
  accountId: {
    type: String,
    required: true
  },
  code: {
    type: String,
    required: true
  },
  timestamp: {
    type: Number,
    required: true
  },
  expiresAt: {
    type: Number,
    required: true
  }
})

// TOTP账户模型
const totpAccountSchema = new mongoose.Schema({
  id: {
    type: String,
    required: true,
    unique: true
  },
  name: {
    type: String,
    required: true
  },
  secret: {
    type: String,
    required: true
  },
  issuer: {
    type: String,
    default: '未知颁发者'
  },
  userId: {
    type: String,
    required: false
  }
})

// 创建索引
totpCodeSchema.index({ accountId: 1, expiresAt: 1 })
totpAccountSchema.index({ id: 1 })

// 导出模型
const db = {
  totpCodes: mongoose.model('TotpCode', totpCodeSchema),
  totpAccounts: mongoose.model('TotpAccount', totpAccountSchema)
}

// 提供批量保存方法
db.totpCodes.bulkSave = async function (codesArray) {
  if (!codesArray || codesArray.length === 0) return

  // 批量插入新文档
  await this.insertMany(codesArray)
}

db.totpAccounts.bulkSave = async function (accountsArray) {
  if (!accountsArray || accountsArray.length === 0) return

  // 对每个账户执行upsert操作
  const operations = accountsArray.map((account) => ({
    updateOne: {
      filter: { id: account.id },
      update: account,
      upsert: true
    }
  }))

  await this.bulkWrite(operations)
}

module.exports = db
